#!/bin/sh
#
# Set up the local machine (Debian or derivative) with the pass-through proxy.
#

set -e

export DEBIAN=ftp.us.debian.org
#
# Replace with better or faster upstream archives, or a full local
# debmarshal repository in /etc/default/debmarshal
#
[ -f /etc/default/debmarshal ] && . /etc/default/debmarshal


CONFIG=/etc/apache2/sites-available/debian-proxy

case "$1" in
    configure)
	a2enmod proxy
	a2enmod disk_cache
	a2enmod proxy_http
	if [ ! -f $CONFIG ] ; then
            cat >$CONFIG <<EOF
#
# generated by debmarshal-debian-proxy package
#
# An apache2 virtualhost configuration to do pass-through proxying to
# the upstream Debian archives.  This makes the host machine
# look like an actual archive server to the client instances, and avoids
# the need to explicitly declare an http_proxy to the installer.
# apt-get and d-i have issues with pipelining to squid caches - proxying
# this way avoids those issues.
#
# You may set variables in /etc/default/debmarshal and regenerate using
#    dpkg-reconfigure debmarshal-debian-proxy
#
# Variables used:
#   DEBIAN     - hostname of a Debian archive, replacing ftp.us.debian.org
#

NameVirtualHost *:80
<VirtualHost *:80>
  ServerName ftp.us.debian.org
  ProxyRequests Off
  ProxyPreserveHost Off

  CacheRoot "/var/www/proxy"
EOF

            if apache2 -v | grep '2\.0' ; then
                cat >>$CONFIG <<EOF
  CacheSize 1024000
  CacheMaxExpire 24
  CacheLastModifiedFactor 0.1
  CacheDefaultExpire 1
EOF
            else
                cat >>$CONFIG <<EOF
  # TODO: cache configuration options here
EOF
            fi

            cat >>$CONFIG <<EOF
  <Proxy *>
    Order deny,allow
    Allow from all
  </Proxy>

  <Directory /debian/>
    ProxyPass http://${DEBIAN}/debian/
    ProxyPassReverse http://${DEBIAN}/debian/
    Allow from all
  </Directory>

  <Directory /debian-security/>
    ProxyPass http://security.debian.org/debian-security/
    ProxyPassReverse http://security.debian.org/debian-security/
    Allow from all
  </Directory>

  LogLevel warn
  CustomLog /var/log/apache2/proxy.log combined

</VirtualHost>
EOF
	    a2ensite debian-proxy
        fi

        if [ ! -d /var/www/proxy ] ; then
            mkdir /var/www/proxy
            chown www-data:www-data /var/www/proxy
        fi

	if which invoke-rc.d >/dev/null 2>&1 ; then
	    invoke-rc.d apache2 force-reload
	else
	    /etc/init.d/apache2 force-reload
	fi
	;;

    abort-upgrade|abort-remove|abort-deconfigure)
        ;;

    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 1
        ;;
esac

#DEBHELPER#
